'nodejs';

const StyleMenu = require('../modules/__style_menu__');
const { dp2px } = require('../modules/__util__');
const MenuWindow = require('../windows/menu_window');


class CircularMenu extends StyleMenu {

    /**
     * 扇形菜单样式
     * @param {MenuWindow} window 
     */
    constructor(window) {
        super(window);
        init(this);
    }

    updateMenuPosition() {
        this.positions = createItemViewPosition(this);
    }

    updateMenuWindow() {
        let window = this.window;
        if (!window.isInit) return null;
        let size = dp2px(this.config.all_item_size);
        let gap = dp2px(this.config.menu_item_gap);
        let padding = dp2px(this.config.all_item_padding);
        //更新悬浮窗大小
        let [x, y] = [gap + size + padding, gap * 2 + size + padding];
        window.setSize(x, y);
        //更新悬浮窗位置
        try {
            let wx = this.fm.logoWindow.getX();
            let wy = this.fm.logoWindow.getY();
            if (!this.config.isLeftMargin) wx -= x;
            window.setPosition(wx + size / 2, wy - y / 2 + size / 2);
        } catch (error) {
            console.error('更新菜单悬浮窗位置失败', error);
        }
    }

    updateMenuAnimation(f) {
        let e = Number(this.config.isLeftMargin);
        let scale = 1 * f
        this.fm.getItemViews().forEach((iv, i) => {
            iv.setTranslationX(this.positions.x[e][i] * f);
            iv.setTranslationY(this.positions.y[e][i] * f);
            iv.setScaleX(scale);
            iv.setScaleY(scale);
        });
    }
}

/** @param {CircularMenu} scope */
function init(scope) {
    scope.updateMenuPosition();
    if (scope.window.isInit) {
        scope.updateMenuWindow();
    }
}

/**
 * 创建菜单ItemViews坐标
 * @author I'm zz
 * @param {CircularMenu} scope 
 */
function createItemViewPosition(scope) {
    let arr = { x: [], y: [] };
    let ivs = scope.fm.getItemViews();
    let gap = dp2px(scope.config.menu_item_gap);
    let len = ivs.length;
    if (!len) return arr;
    let angle = scope.config.angle / (len - 1);
    let firstAngle = 90 - scope.config.angle / 2;
    let degree, value, x, y;
    for (let i = 0; i < 2; i++) {
        degree = i ? firstAngle : 360 - firstAngle;
        arr.x[i] = [];
        arr.y[i] = [];
        for (let e = 0; e < len; e++) {
            value = degree * Math.PI / 180;
            x = parseInt(gap * Math.sin(value));
            y = -parseInt(gap * Math.cos(value));
            arr.x[i][e] = (Math.abs(x) < 10 ? 0 : x);
            arr.y[i][e] = (Math.abs(y) < 10 ? 0 : y);
            i ? degree += angle : degree -= angle;
        }
    }
    return arr;
}

module.exports = CircularMenu;
